<template>
  <div class="dashboard-container">
    <div class="header">
      <h1>仪表盘</h1>
      <div class="date-range">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="fetchDashboardData"
          value-format="YYYY-MM-DD"
        />
      </div>
    </div>
    
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon sales">
          <el-icon><TrendCharts /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">销售总额</div>
          <div class="stat-value">¥{{ totalSales.toFixed(2) }}</div>
          <div class="stat-change" :class="salesChange > 0 ? 'positive' : 'negative'">
            <el-icon><component :is="salesChange > 0 ? ArrowUp : ArrowDown" /></el-icon>
            {{ Math.abs(salesChange) }}%
          </div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon orders">
          <el-icon><ShoppingBag /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">订单总数</div>
          <div class="stat-value">{{ totalOrders }}</div>
          <div class="stat-change" :class="ordersChange > 0 ? 'positive' : 'negative'">
            <el-icon><component :is="ordersChange > 0 ? ArrowUp : ArrowDown" /></el-icon>
            {{ Math.abs(ordersChange) }}%
          </div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon users">
          <el-icon><User /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">用户总数</div>
          <div class="stat-value">{{ totalUsers }}</div>
          <div class="stat-change" :class="usersChange > 0 ? 'positive' : 'negative'">
            <el-icon><component :is="usersChange > 0 ? ArrowUp : ArrowDown" /></el-icon>
            {{ Math.abs(usersChange) }}%
          </div>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon products">
          <el-icon><Goods /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-label">商品总数</div>
          <div class="stat-value">{{ totalProducts }}</div>
          <div class="stat-change" :class="productsChange > 0 ? 'positive' : 'negative'">
            <el-icon><component :is="productsChange > 0 ? ArrowUp : ArrowDown" /></el-icon>
            {{ Math.abs(productsChange) }}%
          </div>
        </div>
      </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-section">
      <div class="chart-container">
        <h2>销售趋势</h2>
        <div class="chart-wrapper">
          <el-chart>
            <el-line
              :data="salesTrendData"
              :dim="['date']"
              :metrics="['sales']"
              smooth
              point-size="4"
              :area="true"
            />
          </el-chart>
        </div>
      </div>
      
      <div class="chart-container">
        <h2>订单状态分布</h2>
        <div class="chart-wrapper">
          <el-chart>
            <el-pie
              :data="orderStatusData"
              angle-field="value"
              color-field="name"
              :radius="0.8"
            />
          </el-chart>
        </div>
      </div>
    </div>
    
    <!-- 最近订单 -->
    <div class="recent-orders">
      <div class="section-header">
        <h2>最近订单</h2>
        <el-button type="text" @click="viewAllOrders">查看全部</el-button>
      </div>
      <el-table :data="recentOrders" style="width: 100%">
        <el-table-column prop="id" label="订单编号" width="120" />
        <el-table-column prop="userId" label="用户ID" width="80" />
        <el-table-column prop="totalAmount" label="订单金额" width="100">
          <template #default="scope">¥{{ scope.row.totalAmount.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="下单时间">
          <template #default="scope">{{ formatDate(scope.row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="80" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewOrderDetail(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 快速操作 -->
    <div class="quick-actions">
      <h2>快速操作</h2>
      <div class="action-buttons">
        <el-button type="primary" size="large" @click="goToProductManagement">
          <el-icon><Goods /></el-icon>
          商品管理
        </el-button>
        <el-button type="primary" size="large" @click="goToOrderManagement">
          <el-icon><ShoppingBag /></el-icon>
          订单管理
        </el-button>
        <el-button type="primary" size="large" @click="goToUserManagement">
          <el-icon><User /></el-icon>
          用户管理
        </el-button>
        <el-button type="primary" size="large" @click="goToCategoryManagement">
          <el-icon><Menu /></el-icon>
          分类管理
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { TrendCharts, ShoppingBag, User, Goods, ArrowUp, ArrowDown, Menu } from '@element-plus/icons-vue';


const router = useRouter();

// 日期范围
const dateRange = ref<string[]>([]);

// 统计数据
const totalSales = ref(0);
const totalOrders = ref(0);
const totalUsers = ref(0);
const totalProducts = ref(0);

// 环比数据
const salesChange = ref(0);
const ordersChange = ref(0);
const usersChange = ref(0);
const productsChange = ref(0);

// 销售趋势数据
const salesTrendData = ref([
  { date: '2024-01-01', sales: 1200 },
  { date: '2024-01-02', sales: 1900 },
  { date: '2024-01-03', sales: 1500 },
  { date: '2024-01-04', sales: 2300 },
  { date: '2024-01-05', sales: 2100 },
  { date: '2024-01-06', sales: 2800 },
  { date: '2024-01-07', sales: 3200 }
]);

// 订单状态分布
const orderStatusData = ref([
  { name: '待支付', value: 25 },
  { name: '已支付', value: 45 },
  { name: '已发货', value: 20 },
  { name: '已完成', value: 60 },
  { name: '已取消', value: 10 }
]);

// 最近订单数据
const recentOrders = ref([
  { id: 1001, userId: 1, totalAmount: 299.99, status: 'paid', createdAt: '2024-01-07T15:30:45Z' },
  { id: 1002, userId: 2, totalAmount: 459.98, status: 'shipped', createdAt: '2024-01-07T14:20:15Z' },
  { id: 1003, userId: 3, totalAmount: 199.99, status: 'pending', createdAt: '2024-01-07T13:10:30Z' },
  { id: 1004, userId: 4, totalAmount: 799.97, status: 'delivered', createdAt: '2024-01-07T12:50:10Z' },
  { id: 1005, userId: 5, totalAmount: 359.99, status: 'cancelled', createdAt: '2024-01-07T11:40:25Z' }
]);

// 加载仪表盘数据
const fetchDashboardData = async () => {
  // 这里应该调用API获取实际数据
  // 目前使用模拟数据
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 模拟数据
    totalSales.value = 15680.50;
    totalOrders.value = 160;
    totalUsers.value = 320;
    totalProducts.value = 85;
    
    salesChange.value = 12.5;
    ordersChange.value = 8.3;
    usersChange.value = 15.2;
    productsChange.value = 5.8;
    
  } catch (error) {
    ElMessage.error('获取仪表盘数据失败');
    console.error('获取仪表盘数据失败:', error);
  }
};

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date);
};

// 获取订单状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    shipped: '已发货',
    delivered: '已完成',
    cancelled: '已取消'
  };
  return statusMap[status] || status;
};

// 获取订单状态标签类型
const getStatusType = (status: string) => {
  const typeMap: Record<string, string> = {
    pending: 'primary',
    paid: 'success',
    shipped: 'info',
    delivered: 'success',
    cancelled: 'danger'
  };
  return typeMap[status] || 'default';
};

// 查看全部订单
const viewAllOrders = () => {
  router.push('/admin/orders');
};

// 查看订单详情
const viewOrderDetail = (orderId: number) => {
  router.push(`/admin/order/${orderId}`);
};

// 跳转到商品管理
const goToProductManagement = () => {
  router.push('/admin/products');
};

// 跳转到订单管理
const goToOrderManagement = () => {
  router.push('/admin/orders');
};

// 跳转到用户管理
const goToUserManagement = () => {
  router.push('/admin/users');
};

// 跳转到分类管理
const goToCategoryManagement = () => {
  router.push('/admin/categories');
};

// 组件挂载时获取数据
onMounted(() => {
  // 设置默认日期范围为最近7天
const endDate = new Date();
const startDate = new Date();
startDate.setDate(startDate.getDate() - 6);

const formatDate = (date: Date): string => {
  return date.toISOString().split('T')[0] ?? '';
};

dateRange.value = [
  formatDate(startDate),
  formatDate(endDate)
];
  
  fetchDashboardData();
});
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.header h1 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
  padding: 0 10px;
}

.stat-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: #fff;
  font-size: 20px;
}

.stat-icon.sales {
  background-color: #1890ff;
}

.stat-icon.orders {
  background-color: #52c41a;
}

.stat-icon.users {
  background-color: #faad14;
}

.stat-icon.products {
  background-color: #f5222d;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-change {
  font-size: 12px;
  display: flex;
  align-items: center;
}

.stat-change.positive {
  color: #52c41a;
}

.stat-change.negative {
  color: #f5222d;
}

.charts-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
  padding: 0 10px;
}

.chart-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart-container h2 {
  font-size: 16px;
  color: #333;
  margin: 0 0 20px 0;
}

.chart-wrapper {
  height: 300px;
}

.recent-orders {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 30px;
  padding: 0 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0 0 0;
}

.section-header h2 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.quick-actions {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 0 10px;
}

.quick-actions h2 {
  font-size: 16px;
  color: #333;
  margin: 0 0 20px 0;
  padding: 20px 0 0 0;
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
  padding-bottom: 20px;
}

.action-buttons .el-button {
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
  }
  
  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .charts-section {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .chart-wrapper {
    height: 250px;
  }
  
  .action-buttons {
    grid-template-columns: 1fr;
    gap: 10px;
  }
}

@media (max-width: 1200px) {
  .charts-section {
    grid-template-columns: 1fr;
  }
}
</style>